<template>
  <div>
    <el-container>
      <el-header class="h-1_7em">
        <div class="pt-0_5em">
          <el-row :gutter="10">
            <el-col :span="2">
              <router-link to="/blog/post/index" class="flex-1">
                <div class="flex-container flex-row-left txt-gray-90 pt-0_25em">
                  <el-icon class="txt-1_1em"> <arrow-left /></el-icon>
                  <span class="">文章管理</span>
                </div>
              </router-link>
            </el-col>
            <el-col :span="16">
              <el-input type="text" placeholder="请输入文章标题" v-model="blogPostDTO.postTitle"></el-input>
            </el-col>
            <el-col :span="2" v-if="blogPostDTO.postStatus === PostStatusEnum.DRAFT.value">
              <el-button type="danger" plain round @click="saveDraft">保存草稿</el-button>
            </el-col>
            <el-col :span="2">
              <el-button type="danger" round @click="submitBlogPost">发布文章</el-button>
            </el-col>
            <el-col :span="2">
              <div class="flex-1">个人头像</div>
            </el-col>
          </el-row>
        </div>
      </el-header>
      <el-main>
        <TinymceEditor v-model="blogPostDTO.postContent"></TinymceEditor>
      </el-main>
    </el-container>
    <el-drawer v-model="showSubmitDrawer" direction="rtl" size="40%" :close-on-click-modal="false">
      <template #header>
        <h4>发布文章</h4>
      </template>
      <template #default>
        <div>
          <el-form :model="blogPostDTO" ref="blogPostDTOForm" label-width="auto">
            <el-form-item label="文章分类" :rules="required" prop="categoryId">
              <el-select v-model="blogPostDTO.categoryId" placeholder="请选择一个分类">
                <el-option v-for="category in categoryList" :label="category.categoryName" :value="category.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="文章标签" :rules="required" prop="tagList">
              <blog-tag-select v-model="blogPostDTO.tagList"></blog-tag-select>
            </el-form-item>
            <el-form-item label="文章摘要" :rules="required" prop="postSummary">
              <el-input type="textarea" v-model="blogPostDTO.postSummary" maxlength="249" :autosize="{ minRows: 4, maxRows: 6 }" show-word-limit />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div class="flex-container flex-row-center">
          <div>
            <el-button class="w-6em" @click="cancelSave">取消</el-button>
          </div>
          <div class="ml-3em">
            <el-button class="w-6em" type="primary" @click="savePost">确定</el-button>
          </div>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ArrowLeft } from '@element-plus/icons-vue'
import TinymceEditor from '@/components/TinymceEditor/index.vue'
import BlogTagSelect from '@/views/blog/post/components/BlogTagSelect.vue'
import { useRoute } from 'vue-router'
import PostStatusEnum from '@/enums/PostStatusEnum'
import BlogPost from '@/api/blog/blogpost'
import { isEmpty, isNotEmpty } from '@/utils/validate'
import { ElMessage, ElMessageBox } from 'element-plus'
import { required } from '@/utils/FormRule'
import Category from '@/api/blog/category'

const route = useRoute()

// 生命周期, 初始化数据
onMounted(() => {
  initBlogPost()
})

// 文章信息
const blogPostDTO = ref({
  id: '',
  categoryId: '',
  postContent: '<span style="color: #909090">【默认内容】</span>',
  postStatus: 0,
  postSummary: '',
  postTitle: '【无标题】',
  tagList: [],
})

function initBlogPost() {
  let { id } = route.query
  if (isNotEmpty(id)) {
    BlogPost.findDetail(id).then(({ result }) => {
      blogPostDTO.value = result
    })
  }
}

// 发布文章的表单信息
const blogPostDTOForm = ref()

// 控制保存草稿或者发布文章的抽屉显示
const showSubmitDrawer = ref(false)

// 分类列表
const categoryList = ref([])

// 发布文章信息
function submitBlogPost() {
  // 对参数进行校验
  if (isEmpty(blogPostDTO.value.postTitle)) {
    ElMessage.error('文章标题不能为空')
    return
  }
  if (isEmpty(blogPostDTO.value.postContent)) {
    ElMessage.error('文章内容不能为空')
    return
  }
  showSubmitDrawer.value = true
  Category.list({}, false).then(({ result }) => {
    categoryList.value = result
  })
}

// 保存草稿
function saveDraft() {
  // 对参数进行校验
  if (isEmpty(blogPostDTO.value.postTitle)) {
    ElMessage.error('文章标题不能为空')
    return
  }
  if (isEmpty(blogPostDTO.value.postContent)) {
    ElMessage.error('文章内容不能为空')
    return
  }
  blogPostDTO.value.postStatus = PostStatusEnum.DRAFT.value
  if (isNotEmpty(blogPostDTO.value.id)) {
    BlogPost.update(blogPostDTO.value)
  } else {
    BlogPost.create(blogPostDTO.value)
  }
}

// 取消保存，关闭抽屉
function cancelSave() {
  showSubmitDrawer.value = false
}
// 发布文章
function savePost() {
  blogPostDTOForm.value.validate(async (valid) => {
    if (valid) {
      blogPostDTO.value.postStatus = PostStatusEnum.PUBLISHED.value
      let { code } = isNotEmpty(blogPostDTO.value.id) ? await BlogPost.update(blogPostDTO.value) : await BlogPost.create(blogPostDTO.value)
      if (code === 200) {
        ElMessageBox.confirm('创建成功，是否继续创作', 'success', {
          confirmButtonText: '继续',
          cancelButtonText: '回到文章管理',
          type: 'success',
          center: true,
        })
          .then(() => {
            ElMessage({
              type: 'success',
              message: 'Delete completed',
            })
          })
          .catch(() => {
            router.push({ path: '/post/index', query: { id } })
          })
      }
    }
  })
}
</script>

<style scoped lang="scss"></style>
